//
//  BIDHousePickerView.m
//  HJGJCommunity
//
//  Created by mal on 2017/5/19.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDHousePickerView.h"
#import "UIView+FindFirstResponder.h"

@interface BIDHousePickerView()<UIPickerViewDelegate, UIPickerViewDataSource>
{
    UIPickerView *_myPicker;
    UIToolbar *_myToolbar;
    BOOL _bShow;
    NSArray *_dataSourceArr;
    NSUInteger _selectRowForFirstComponent;
    NSUInteger _selectRowForSecondComponent;
    NSUInteger _selectRowForThirdComponent;
    NSUInteger _selectRowForFourthComponent;
    NSMutableArray *_areaArr;
    NSMutableArray *_floorArr;
    NSMutableArray *_unitArr;
    NSMutableArray *_codeArr;
    //区域
    NSString *_area;
    //楼号
    NSString *_floor;
    //单元
    NSString *_unit;
    //房号
    NSString *_code;
}

@end

@implementation BIDHousePickerView

@synthesize delegate;
@synthesize bIsInputView;

- (id)initWithMenuArr:(NSArray *)arr
{
    self = [super init];
    if(self)
    {
        _dataSourceArr = [[NSArray alloc] initWithArray:arr];
        _area = _dataSourceArr[0][@"name"];
        [self initView];
        _areaArr = [[NSMutableArray alloc] initWithArray:_dataSourceArr];
        [self fetchHouseInfoByLevel:1 filter:_area];
        [self fetchHouseInfoByLevel:2 filter:_floor];
        [self fetchHouseInfoByLevel:3 filter:_unit];
    }
    return self;
}

- (void)initView
{
    self.autoresizesSubviews = NO;
    _selectRowForFirstComponent = 0;
    _selectRowForSecondComponent = 0;
    _selectRowForThirdComponent = 0;
    _selectRowForFourthComponent = 0;
    _floorArr = [NSMutableArray array];
    _unitArr = [NSMutableArray array];
    _codeArr = [NSMutableArray array];
    //
    _bShow = NO;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGRect ownFrame = self.frame;
    ownFrame.size.width = screenSize.width;
    ownFrame.size.height = 246.0f;
    ownFrame.origin.x = 0;
    ownFrame.origin.y = screenSize.height;
    self.frame = ownFrame;
    
    //myToolBar
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBtnHandler)];
    item1.tintColor = [UIColor whiteColor];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(confirmBtnHandler)];
    item3.tintColor = [UIColor whiteColor];
    _myToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, ownFrame.size.width, 44.0f)];
    [_myToolbar setItems:[[NSArray alloc] initWithObjects:item1, item2, item3, nil]];
    _myToolbar.barStyle = UIBarStyleBlack;
    [self addSubview:_myToolbar];
    
    //pickerView
    CGSize pickerSize = CGSizeMake(screenSize.width, 216.0f);
    _myPicker = [[UIPickerView alloc] initWithFrame:CGRectMake((ownFrame.size.width-pickerSize.width)/2, _myToolbar.frame.size.height, pickerSize.width, pickerSize.height)];
    [_myPicker setBackgroundColor:[UIColor whiteColor]];
    _myPicker.dataSource = self;
    _myPicker.delegate = self;
    _myPicker.showsSelectionIndicator = YES;
    [_myPicker selectRow:0 inComponent:0 animated:NO];
    [self addSubview:_myPicker];
}

- (void)confirmBtnHandler
{
    _bShow = NO;
    __block CGRect frame1 = self.frame;
    
    NSUInteger row = [_myPicker selectedRowInComponent:0];
    NSDictionary *dic = _areaArr[row];
    NSString *area_code = dic[@"value"];
    //
    row = [_myPicker selectedRowInComponent:1];
    dic = _floorArr[row];
    NSString *floor_code = dic[@"value"];
    //
    row = [_myPicker selectedRowInComponent:2];
    dic = _unitArr[row];
    NSString *unit_code = dic[@"value"];
    //
    row = [_myPicker selectedRowInComponent:3];
    dic = _codeArr[row];
    NSString *code_code = dic[@"value"];
    //
    NSString *strHouseName = [[NSString alloc] initWithFormat:@"%@-%@-%@-%@", _area, _floor, _unit, _code];
    NSString *strHouseCode = [[NSString alloc] initWithFormat:@"%@-%@-%@-%@", area_code, floor_code, unit_code, code_code];
    if(bIsInputView)
    {
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        UITextField *tf = (UITextField*)[keyWindow findFirstResponder];
        [tf resignFirstResponder];
        if([delegate respondsToSelector:@selector(chooseHouseName:houseCode:)])
        {
            [delegate chooseHouseName:strHouseName houseCode:strHouseCode];
        }
    }
    else
    {
        [UIView animateWithDuration:0.35f animations:^{frame1.origin.y=[UIScreen mainScreen].bounds.size.height;self.frame = frame1;} completion:^(BOOL finished){
            if([delegate respondsToSelector:@selector(chooseHouseName:houseCode:)])
            {
                [delegate chooseHouseName:strHouseName houseCode:strHouseCode];
            }
            [self removeFromSuperview];
        }];
    }
}

- (void)cancelBtnHandler
{
    if(bIsInputView)
    {
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        UITextField *tf = (UITextField*)[keyWindow findFirstResponder];
        [tf resignFirstResponder];
    }
    else
    {
        [self dismissView];
    }
}

- (void)showView
{
    if(!_bShow)
    {
        _bShow = YES;
        UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
        
        __block CGRect frame1 = self.frame;
        [keyWindow addSubview:self];
        [UIView animateWithDuration:0.6f animations:^{frame1.origin.y = [UIScreen mainScreen].bounds.size.height-246; self.frame = frame1;}];
    }
}

- (void)dismissView
{
    _bShow = NO;
    __block CGRect frame1 = self.frame;
    [UIView animateWithDuration:0.35f animations:^{frame1.origin.y=[UIScreen mainScreen].bounds.size.height;self.frame = frame1;} completion:^(BOOL finished){[self removeFromSuperview];}];
}

- (NSArray *)fetchHouseInfoByLevel:(NSUInteger)level filter:(NSString *)filter
{
    NSArray *arr = nil;
    NSArray *filterArr = nil;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name==%@", filter];
    if(level == 1)
    {
        filterArr = [_areaArr filteredArrayUsingPredicate:predicate];
        if(filterArr.count > 0)
        {
            NSDictionary *dic = filterArr[0];
            if(ISNULL(dic[@"linkStr"]))
            {
                _floorArr = [NSMutableArray array];
                _unitArr = [NSMutableArray array];
                _codeArr = [NSMutableArray array];
                _floor = @"";
            }
            else
            {
                _floorArr = [[NSMutableArray alloc] initWithArray:dic[@"linkStr"]];
                _floor = _floor.length>0 ? _floor : _floorArr[0][@"name"];
            }
            arr = _floorArr;
        }
    }
    else if(level == 2)
    {
        filterArr = [_floorArr filteredArrayUsingPredicate:predicate];
        if(filterArr.count > 0)
        {
            NSDictionary *dic = filterArr[0];
            if(ISNULL(dic[@"linkStr"]))
            {
                _unitArr = [NSMutableArray array];
                _codeArr = [NSMutableArray array];
                _unit = @"";
            }
            else
            {
                _unitArr = [[NSMutableArray alloc] initWithArray:dic[@"linkStr"]];
                _unit = _unit.length>0 ? _unit :_unitArr[0][@"name"];
            }
            arr = _unitArr;
        }
    }
    else if(level == 3)
    {
        filterArr = [_unitArr filteredArrayUsingPredicate:predicate];
        if(filterArr.count > 0)
        {
            NSDictionary *dic = filterArr[0];
            if(ISNULL(dic[@"linkStr"]))
            {
                _codeArr = [NSMutableArray array];
                _code = @"";
            }
            else
            {
                _codeArr = [[NSMutableArray alloc] initWithArray:dic[@"linkStr"]];
                _code = _code.length>0 ? _code : _codeArr[0][@"name"];
            }
            arr = _codeArr;
        }
    }
    return arr;
}

#pragma mark UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 4;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSInteger count = 0;
    if(component == 0)
    {
        count = _areaArr.count;
    }
    else if(component == 1)
    {
        count = _floorArr.count;
    }
    else if(component == 2)
    {
        count = _unitArr.count;
    }
    else if(component == 3)
    {
        count = _codeArr.count;
    }
    return count;
}

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *strMenu = @"";
    switch(component)
    {
        case 0:
        {
            strMenu = _dataSourceArr[row][@"name"];
        }
            break;
        case 1:
        {
            strMenu = _floorArr[row][@"name"];
        }
            break;
        case 2:
        {
            strMenu = _unitArr[row][@"name"];
        }
            break;
        case 3:
        {
            strMenu = _codeArr[row][@"name"];
        }
            break;
    }
    return strMenu;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(component == 0)
    {
        //区域
        if(row == _selectRowForFirstComponent)
        {}
        else
        {
            _selectRowForFirstComponent = row;
            _area = _dataSourceArr[row][@"name"];
            _floor = @"";
            _unit = @"";
            _code = @"";
            [self fetchHouseInfoByLevel:1 filter:_area];
            [self fetchHouseInfoByLevel:2 filter:_floor];
            [self fetchHouseInfoByLevel:3 filter:_unit];

            [_myPicker reloadComponent:1];
            [_myPicker reloadComponent:2];
            [_myPicker reloadComponent:3];
        }
    }
    else if(component == 1)
    {
        //楼号
        if(row == _selectRowForSecondComponent)
        {}
        else
        {
            _selectRowForSecondComponent = row;
            _floor = _floorArr[row][@"name"];
            _unit = @"";
            _code = @"";
            //根据楼号获取单元
            [self fetchHouseInfoByLevel:2 filter:_floor];
            //根据单元获取房号
            [self fetchHouseInfoByLevel:3 filter:_unit];
            [_myPicker reloadComponent:2];
            [_myPicker reloadComponent:3];
        }
    }
    else if(component == 2)
    {
        //单元
        if(row == _selectRowForThirdComponent)
        {}
        else
        {
            _selectRowForThirdComponent = row;
            _unit = _unitArr[row][@"name"];
            _code = @"";
            [self fetchHouseInfoByLevel:3 filter:_unit];
            [_myPicker reloadComponent:3];
        }
    }
    else if(component == 3)
    {
        //房号
        if(row == _selectRowForFourthComponent)
        {}
        else
        {
            _selectRowForFourthComponent = row;
            _code = _codeArr[row][@"name"];
            _selectRowForFourthComponent = row;
        }
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    CGFloat width = 0;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    NSUInteger averageWidth = screenSize.width / 4;
    switch(component)
    {
        case 0:
        {
            width = 60;
        }
            break;
        case 1:
        {
            width = averageWidth;
        }
            break;
        case 2:
        {
            width = averageWidth;
        }
            break;
        case 3:
        {
            width = screenSize.width-60-averageWidth*2;
        }
            break;
    }
    return width;
}

@end
